<template>
  <div class="inform-container">
    <h1>消息中心 (API 测试)</h1>

    <div class="controls">
      <el-button @click="fetchData" :loading="loading">手动刷新</el-button>
      <el-button @click="handleMarkAllRead" type="primary">全部已读</el-button>
    </div>

    <div v-if="loading" class="loading-text">
      消息加载中...
    </div>

    <div v-if="error" class="error-text">
      发生错误: {{ error }}
    </div>

    <div v-if="!loading && messageData" class="data-display">
      <h2>消息列表:</h2>
      <p>总数: {{ messageData.total }}</p>

      <div v-if="messageData.records.length > 0">
        <div v-for="msg in messageData.records" :key="msg.id" class="message-item">
          <h3>{{ msg.title }} - (状态: {{ msg.status === 0 ? '未读' : '已读' }})</h3>
          <p>{{ msg.content }}</p>
          <small>{{ msg.createTime }}</small>
          <el-button v-if="msg.status === 0" size="small" @click="handleMarkOneRead(msg.id)">
            标记已读
          </el-button>
        </div>
      </div>
      <div v-else>
        <p>暂无消息</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getMessagePage, markAllMessagesAsRead, markMessageAsRead } from '@/api/inform';
import type { IMessagePageResult } from '@/types/inform';

const loading = ref(false);
const error = ref<string | null>(null);
const messageData = ref<IMessagePageResult | null>(null);

const fetchData = async () => {
  loading.value = true;
  error.value = null;
  messageData.value = null;
  try {
    const response = await getMessagePage({ page: 1, pageSize: 10 });
    messageData.value = response.data;
  } catch (e: any) {
    error.value = e.message || '获取消息列表失败';
  } finally {
    loading.value = false;
  }
};

const handleMarkAllRead = async () => {
  try {
    await markAllMessagesAsRead();
    ElMessage.success('全部标记已读成功！');
    fetchData(); // 重新加载数据以更新状态
  } catch (e: any) {
    ElMessage.error(e.message || '操作失败');
  }
};

const handleMarkOneRead = async (id: number) => {
  try {
    await markMessageAsRead(id);
    ElMessage.success('标记已读成功！');
    fetchData(); // 重新加载数据以更新状态
  } catch (e: any) {
    ElMessage.error(e.message || '操作失败');
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.inform-container {
  padding: 20px;
  font-family: sans-serif;
}
.controls {
  margin-bottom: 20px;
}
.loading-text, .error-text {
  padding: 20px;
  border-radius: 4px;
}
.message-item {
  background-color: #f4f4f4;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 10px;
}
</style>
